#include <stdio.h>
#define min(x, y) (x) >= (y) ? (y) : (x)
size_t MyString(const char *s)
{
    size_t count = 0;
    while (*s != 0)
    {
        s++;
        count++;
    }
    return count;
}

int mySringcmp(const char *s1, const char *s2)
{
    while (*s1 == *s2 && *s1 != '\0' && *s2 != '\0')
    {
        s1++;
        s2++;
    }
    return *s1 - *s2;
}
int mySringncmp(const char *s1, const char *s2, int n)
{
    n = min(min(MyString(s1), MyString(s2)), n);
    while (*s1 == *s2 && n != 1)
    {
        s1++;
        s2++;
        n--;
    }

    return *s1 - *s2;
}
void Strcpy(char *dest, const char *src)
{
    while (*src != 0)
    {
        *dest = *src;
        dest++;
        src++;
    }
    *dest = '\0';
}
char *Stycat(char *dest, const char *src)
{
    Strcpy(dest + MyString(dest), src);
}

char *mystrstr(char *dest, const char *src)
{
    size_t dlen = MyString(dest);
    size_t slen = MyString(src);
    if (dlen < slen)
    {
        return NULL;
    }
    for (int i = 0; i <= dlen - slen; i++)
    {
        if (mySringncmp(dest + i, src, slen) == 0)
        {
            return dest + i;
        }
    }
    return NULL;
}
char *mystrtok(char *src, char *delim)
{
    static char *nextstr = NULL;
    if (src == NULL)
    {
        src = nextstr;
    }
    if (src == NULL)
    {
        return NULL;
    }
    while (*src != '\0')
    {
        char temp[] = {*src, '\0'};
        // 当前字母为分隔符
        if (mystrstr(delim, temp) != NULL)
        {
            src++;
        }
        else
        {
            break;
        }
    }
    if (*src == '\0')
    {
        return NULL;
    }
    // 有效字符串首地址
    char *end = src;
    while (*end != '\0')
    {
        char temp[] = {*end, '\0'};
        if (mystrstr(delim, temp) != NULL)
        {
            break;
        }
        else
        {
            end++;
        }
    }
    // 字符串结尾
    if (*end == '\0')
    { // 下一个切割的不存在
        nextstr = NULL;
    }
    else
    {
        *end = '\0';
        nextstr = end + 1;
    }
    return src;
}

int main()
{
    printf("%ld\n", MyString("hello"));
    printf("%d\n", min(3, 2));
    char s1[] = "hell";
    char s2[] = "hell";
    char s3[] = "he,l!l.o";
    char *dest = mystrstr(s1, s2);
    printf("%d\n", mySringncmp(s1, s2, 5));
    printf("%s\n", mystrtok(s3, ",!."));
    printf("%s\n", mystrtok(NULL, ",!."));
    printf("%s\n", mystrtok(NULL, ",!."));
    printf("%s\n", mystrtok(NULL, ",!."));
    printf("%s\n", mystrtok(NULL, ",!."));
    return 0;
}